package com.superm.service.impl;

import com.alibaba.fastjson.JSONArray;
import com.superm.entity.*;
import com.superm.mappers.*;
import com.superm.service.PurchaseService;
import com.superm.utils.Tool;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;


@Service
public class PurchaseServiceImpl implements PurchaseService {


    @Autowired
    private PurchaseMapper purchaseMapper;

    @Autowired
    private PurchaseDetailsMapper purchaseDetailsMapper;

    @Autowired
    private StockMapper stockMapper;

    @Autowired
    private RepostoryMapper repostoryMapper;

    @Autowired
    private GodownEntryMapper godownEntryMapper;

    @Autowired
    private WarehouseExitMapper warehouseExitMapper;
    /**
     * 实现添加采购申请单
     * @param purchasePoJo
     * @param purcheaseDetails
     * @return
     */
    @Override
    public Map<String, Object> addPurchase(PurchasePoJo purchasePoJo, List<String> purcheaseDetails) {
        Map<String,Object> map = new HashMap<String,Object>();
        //获取认证主体
        Subject subjet = SecurityUtils.getSubject();
        //从认证主体取出认证信息
        Emp emp = (Emp)subjet.getPrincipal();
        //替换值
        Purchase purchase = new Purchase();
        BeanUtils.copyProperties(purchasePoJo,purchase);
        //经办人
        purchase.setEmp(new Emp(emp.geteId()));
        //入库仓库
        purchase.setRepostoryType(new RepostoryType(purchasePoJo.getRepostoryType()));
        //编号随机数生成
        purchase.setPurCode(Tool.dateRandom("CG"));
        //供应商
        purchase.setSupplier(new Supplier(purchasePoJo.getSupplier()));
        //将详情信息转换为对象信息
        List<PurchaseDetailsPoJo> purchaseDetailsPoJos = JSONArray.parseArray(purcheaseDetails.toString(),PurchaseDetailsPoJo.class);
        //添加采购单
        if (purchaseMapper.addMationInFo(purchase)>0){
            //循环详情信息
            purchaseDetailsPoJos.forEach(purchaseDetail->{
                PurchaseDetails purchaseDetails = new PurchaseDetails();
                purchaseDetails.setPurchase(new Purchase(purchase.getPurCode()));
                purchaseDetails.setGoods(new Goods(purchaseDetail.getGoods()));
                purchaseDetails.setPurchaseCount(purchaseDetail.getPurchaseCount());
                purchaseDetails.setPurchasingPrice(purchaseDetail.getPurchasingPrice());
                purchaseDetails.setPurchasetotalPrice(purchaseDetail.getPurchasetotalPrice());

                //添加详情
                purchaseDetailsMapper.addMationInfo(purchaseDetails);
            });

                map.put("code",0);
                map.put("success",true);
                map.put("msg","采购申请成功!");
        }


        return map;
    }

    /**
     * 采购申请单查询实现
     * @param purchasePoJo
     * @return
     */
    @Override
    public Map<String, Object> likePurshace(PurchasePoJo purchasePoJo,Integer pageNo,Integer pageSize) {
        Map<String,Object> map = new HashMap<>();
        Purchase purchase = new Purchase();
        BeanUtils.copyProperties(purchasePoJo,purchase);
        //申请人
        purchase.setEmp(new Emp(purchasePoJo.getEmp()));
        map.put("code",0);
        map.put("count",purchaseMapper.count(purchase));
        map.put("data",purchaseMapper.likeMationInfo(purchase,(pageNo-1)*pageSize,pageSize));
        return map;
    }

    /**
     * 采购单改为经理已审批
     * @param purCode
     * @return
     */
    @Override
    public Map<String,Object> purchaseState1(String purCode){
          Map<String,Object> map = new HashMap<String,Object>();
          if (purchaseMapper.updateState1(purCode)>0){
              map.put("success",true);
              map.put("msg","审批成功!");
          }
        return map;
    }

    /**
     * 实现采购单改为财务打款审批
     * @param purCode
     * @return
     */
    @Override
    public Map<String, Object> purchaseState2(String purCode) {
        Map<String,Object> map = new HashMap<>();
        if (purchaseMapper.updateState2(purCode)>0){
            map.put("success",true);
            map.put("msg","审批打款成功!");
        }
        return map;
    }

    /**
     * 实现采购员采购
     * @param purCode
     * @return
     */
    @Override
    public Map<String, Object> purchaseState3(String purCode) {
        Map<String,Object> map = new HashMap<String,Object>();
        if (purchaseMapper.updateState3(purCode)>0){
            map.put("success",true);
            map.put("msg","已采购!");
        }
        return map;
    }

    /**
     * 改变状态4
     * @param purCode
     * @return
     */
    @Override
    public Map<String, Object> purchaseState4(String purCode) {
        Map<String,Object> map = new HashMap<String,Object>();
        if (purchaseMapper.updateState4(purCode)>0){
            map.put("success",true);
            map.put("msg","退货成功!");
        }
        return map;
    }

    /**
     * 实现采购单被驳回
     * @param purCode
     * @param role
     * @return
     */
    @Override
    public Map<String, Object> purchaseState5(String purCode, String role) {
       Map<String,Object> map = new HashMap<String,Object>();
       if (purchaseMapper.updateState5(purCode,role)>0){
            map.put("success",true);
            map.put("msg","已驳回!");
       }
        return map;
    }

    /**
     * 实现采购单入库
     * @param purCode
     * @param remarkes
     * @return
     */
    @Override
    public Map<String, Object> goodsWraehousing(String purCode, String remarkes) {
        Map<String,Object> map = new HashMap<String,Object>();
        //根据订单查询指定订单信息
        Purchase purchase = purchaseMapper.selectIdMationInfo(purCode);
        //根据订单查询所有详情信息
        List<PurchaseDetails> purchaseDetails = purchaseDetailsMapper.selectCodeMationOne(purCode);
        //循环详情信息
        //向库存表添加信息
        purchaseDetails.forEach(purchaseDetail->{
            //查询是否有此商品的库存信息,如果有,直接把对象拿出来,执行update语句对库存进行叠加,如为空,执行insert语句添加
            Stock stock = stockMapper.selectGoodsIdAndRepostoryId(purchaseDetail.getGoods().getGoodsId(),purchase.getRepostoryType().getReponseTypePid());
            if (stock!=null){
                //执行update修改库存数量
                Stock stock1  = new Stock();
                stock1.setStockCount(purchaseDetail.getPurchaseCount());
                stock1.setStockId(stock.getStockId());
                stock1.setSupplierid(purchase.getSupplier().getSupplierId());
                //采购进价
                stock1.setPurchasePrice(purchaseDetail.getPurchasingPrice());
                stockMapper.updateMationInfo(stock1);
            }else{
                //执行insert新增库存
                Stock stock2 = new Stock();
                stock2.setStockCount(purchaseDetail.getPurchaseCount());
                stock2.setStockwarnCount(100);
                stock2.setGoodsid(purchaseDetail.getGoods().getGoodsId());
                stock2.setReponseid(purchase.getRepostoryType().getReponseTypePid());
                stock2.setSupplierid(purchase.getSupplier().getSupplierId());
                //采购进价
                stock2.setPurchasePrice(purchaseDetail.getPurchasingPrice());
                stockMapper.addInventory(stock2);
            }
        });
        //增加仓库已用容量
        if ( repostoryMapper.ZRepcapCityxhao(purchase.getCapacity(),purchase.getRepostoryType().getReponseTypePid())>0){
            //获取认证主体
            Subject subjet = SecurityUtils.getSubject();
            //从认证主体取出认证信息
            Emp emp = (Emp)subjet.getPrincipal();
            GodownEntry godownEntry = new GodownEntry();
            godownEntry.setPurchase(new Purchase(purCode));
            godownEntry.setEmp(emp);
            godownEntry.setRemarkes(remarkes);
                //添加入库单
              if (godownEntryMapper.addMationInfo(godownEntry)>0){
                  //改变采购单状态
                  if (purchaseMapper.updateState4(purCode)>0){
                      map.put("code",0);
                      map.put("success",true);
                      map.put("msg","入库成功!");
                  }
              }
        }
        return map;
    }

    /**
     * 实现采购退货单出库
     * @param purCode
     * @param remarkes
     * @return
     */
    @Override
    public Map<String, Object> purchaseOutBound(String purCode, String remarkes){
        Map<String,Object> map = new HashMap<String,Object>();
        //根据订单查询指定订单信息
        Purchase purchase = purchaseMapper.selectIdMationInfo(purCode);
        //根据订单查询所有详情信息
        List<PurchaseDetails> purchaseDetails = purchaseDetailsMapper.selectCodeMationOne(purCode);
        //循环详情信息
        //对库存表的信息进行减少
        purchaseDetails.forEach(purchaseDetail->{
            //查询到该商品的库存信息
            Stock stock = stockMapper.selectGoodsIdAndRepostoryId(purchaseDetail.getGoods().getGoodsId(),purchase.getRepostoryType().getReponseTypePid());
            System.out.println("库存号:"+stock);
            //对库存进行减少
            stockMapper.decreaseStock(stock.getStockId(),purchaseDetail.getPurchaseCount());
        });



        //库存已减少,然后仓库已用容量减少
        if ( repostoryMapper.XRepcapCityxhao(purchase.getCapacity(),purchase.getRepostoryType().getReponseTypePid())>0){
            //获取认证主体
            Subject subjet = SecurityUtils.getSubject();
            //从认证主体取出认证信息
            Emp emp = (Emp)subjet.getPrincipal();
            WarehouseExit warehouseExit = new WarehouseExit();
            warehouseExit.setPurchase(new Purchase(purCode));
            warehouseExit.setEmp(emp);
            warehouseExit.setRemarkes(remarkes);
            warehouseExit.setGoodsTotalCount(purchase.getGoodstotalCount());
            //添加采购退货出库单
            if (warehouseExitMapper.addWarehouseExit(warehouseExit)>0){
                //改变采购退货单状态
                if (purchaseMapper.updateState3(purCode)>0){
                    map.put("code",0);
                    map.put("success",true);
                    map.put("msg","出库成功!");
                }
            }
        }
        return map;
    }
}
